import sys, os, math, random
import pygame
from pygame.locals import *

import globals
from debugger import *
from vector import *
from camera import *
from menu import *
from stars import *
from player import *
from meteor import *
from static import *

class Game:

	def __init__(self, debug):
		pygame.init()

		self.console = Debugger(self, debug)
		
		self.world = pygame.Rect(0, 0, 10000, 10000)

		self.resolutions = pygame.display.list_modes()
		self.window = pygame.display.set_mode(self.resolutions[0], pygame.FULLSCREEN)

		self.screen = pygame.display.get_surface()
		self.screen.set_alpha(255, pygame.RLEACCEL)
		self.screen_rect = self.screen.get_rect()

		pygame.display.set_caption(globals.game['title'])
		pygame.mouse.set_visible(False)
		pygame.mouse.set_pos(self.screen_rect.center)
		pygame.event.set_grab(1)

		self.fps = globals.game['fps']
		self.dt = 1.0 / self.fps
		self.clock = pygame.time.Clock()
		self.running = True

		self.sprites = pygame.sprite.OrderedUpdates()

		# Physics
		self.gravity = globals.physics['gravity']

		self.initObjects()
		

	def initObjects(self):
		self.menu = Menu(self)
		
		self.stars = Stars(self, 3, 10000)
		
		player_pos = Vector(self.world.centerx, self.world.centery)
		self.player = Player(self, player_pos)
		
		meteor = Meteor(self)
		meteor.apply_force(Vector(15.0, 15.0))
		
		self.sprites.add(meteor)
		self.sprites.add(self.player)
		
		self.background = pygame.Surface(self.screen.get_size()).convert()
		self.background.fill((0, 0, 0))
		
		self.camera = Camera(self, self.screen_rect, self.player)


	def event(self, events):
		#pressed = pygame.key.get_pressed()
			
		for event in events:
			if event.type == QUIT:
				self.running = False
			elif event.type == KEYDOWN:
				if event.key == K_ESCAPE:
					self.running = False


	def draw(self):
		#self.menu.draw()
		
		self.stars.draw()

		for sprite in self.sprites:
			sprite.draw()

		self.console.draw()


	def update(self):
		self.sprites.update()
		self.camera.update()


	def run(self):
		while self.running:
			self.screen.blit(self.background, (0, 0))
			self.event(pygame.event.get())

			self.update()
			
			self.console.log('FPS: ' + str(self.clock.get_fps()))
			
			self.draw()
			pygame.display.flip()
			
			self.clock.tick(self.fps)


		pygame.quit()




if (__name__ == '__main__'):

	debug = False
	if len(sys.argv) > 1:
		if sys.argv[1] == '-d': debug = True

	game = Game(debug)
	game.run()

